package com.sdsy.blockchaintrainingback.service.user;

import com.sdsy.blockchaintrainingback.enums.CommonStatusEnum;
import com.sdsy.blockchaintrainingback.pojo.user.User;
import com.sdsy.blockchaintrainingback.service.user.AuthService;
import com.sdsy.blockchaintrainingback.service.user.UserService;
import com.sdsy.blockchaintrainingback.vo.auth.AuthLoginReqVO;
import com.sdsy.blockchaintrainingback.vo.auth.AuthLoginRespVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import static com.sdsy.blockchaintrainingback.exception.enums.ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS;
import static com.sdsy.blockchaintrainingback.exception.enums.ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED;
import static com.sdsy.blockchaintrainingback.exception.utils.ServiceExceptionUtil.exception;
import static com.sdsy.blockchaintrainingback.utils.JwtUtil.generateToken;

/**
 * @Description TODO
 * @Author linzili
 * @Date 2023/9/24 22:13
 * @Version 1.0
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Resource
    private UserService userService;

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        User user= userService.getUserByUsername(reqVO.getUsername());
        if(user == null) {
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if(!userService.isPasswordMatch(reqVO.getPassword(),user.getPassword())){
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if(ObjectUtils.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())){
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }

        return createTokenAfterLoginSuccess(user.getId(),user.getUsername());
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId,String username) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("username",username);
        String token = generateToken(map);
        AuthLoginRespVO respVO = new AuthLoginRespVO();
        respVO.setUserId(userId);
        respVO.setAccessToken(token);
        return  respVO;
    }
}
